package thread;

public class ThreadYieldJoinDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new WorkerThread("辅助线程1"));
        Thread thread2 = new Thread(new WorkerThread("辅助线程2"));

        thread1.start();
        thread2.start();

        // 主线程随机决定是否让出或等待线程1和2
        for (int i = 0; i < 100; i++) {
            if (Math.random() > 0.5) {
                Thread.yield(); // 主线程让出CPU,并不保证线程会立即让出
                System.out.println("测试线程礼让");
            } else {
                try {
                    thread1.join(100); // 主线程等待线程1继续运行最多100ms
                    System.out.println("测试线程等待线程1");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        // join方法:等待线程的完成,不是抢占
        try {
            thread1.join(); // 确保主线程等待线程1执行完毕
            thread2.join(); // 确保主线程等待线程2执行完毕
            System.out.println("所有线程已完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



    // 模拟线程运行
    static class WorkerThread implements Runnable {
        private String threadName;

        public WorkerThread(String threadName) {
            this.threadName = threadName;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println(threadName + " 正在运行: " + i);
                try {
                    Thread.sleep(1); // 休眠1毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
